<template>
  <div class="permission-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>权限管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="权限名称">
          <a-input
            v-model:value="searchForm.permissionName"
            placeholder="请输入权限名称"
            style="width: 200px"
            @press-enter="handleSearch"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="资源类型">
          <a-select
            v-model:value="searchForm.resourceType"
            placeholder="请选择资源类型"
            style="width: 150px"
            allow-clear
          >
            <a-select-option value="menu">菜单</a-select-option>
            <a-select-option value="button">按钮</a-select-option>
            <a-select-option value="api">接口</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
            allow-clear
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch" :loading="loading">搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset" :loading="loading">重置</a-button>
        </a-form-item>
      </a-form>
      
      <!-- 搜索结果提示 -->
      <div v-if="searchResultInfo" class="search-result-info">
        <a-alert :message="searchResultInfo" type="info" show-icon closable />
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <a-button type="primary" @click="showCreateModal">
        <template #icon><PlusOutlined /></template>
        新增权限
      </a-button>
      <a-button @click="expandAll">展开全部</a-button>
      <a-button @click="collapseAll">收起全部</a-button>
    </div>

    <!-- 权限树表格 -->
    <a-table
      :columns="permissionTableColumns"
      :data-source="permissionList"
      :pagination="false"
      :loading="loading"
      row-key="id"
      :expanded-row-keys="expandedKeys"
      @expand="onExpand"
      size="middle"
    >
      <!-- 权限名称列 -->
      <template #permissionName="{ record }">
        <span :style="{ paddingLeft: (record.level || 0) * 20 + 'px' }">
          {{ record.permissionName }}
        </span>
      </template>

      <!-- 资源类型列 -->
      <template #resourceType="{ record }">
        <a-tag :color="getResourceTypeColor(record.resourceType)">
          <template #icon>
            <component :is="getResourceTypeIcon(record.resourceType)" />
          </template>
          {{ getResourceTypeText(record.resourceType) }}
        </a-tag>
      </template>

      <!-- 状态列 -->
      <template #status="{ record }">
        <a-switch
          :checked="record.status === 1"
          @change="(checked) => handleStatusChange(record, checked)"
          checked-children="启用"
          un-checked-children="禁用"
        />
      </template>

      <!-- 操作列 -->
      <template #action="{ record }">
        <a-space>
          <a-button type="link" size="small" @click="showEditModal(record)">
            编辑
          </a-button>
          <a-button type="link" size="small" @click="showCreateModal(record)">
            新增子权限
          </a-button>
          <a-popconfirm
            title="确定要删除这个权限吗？"
            @confirm="handleDelete(record)"
          >
            <a-button type="link" size="small" danger>
              删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>

    <!-- 新增/编辑权限模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="上级权限" name="parentId">
          <a-tree-select
            v-model:value="formData.parentId"
            :tree-data="parentPermissionOptions"
            placeholder="请选择上级权限（可选）"
            allow-clear
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item label="权限名称" name="permissionName">
          <a-input v-model:value="formData.permissionName" placeholder="请输入权限名称" />
        </a-form-item>
        <a-form-item label="权限编码" name="permissionCode">
          <a-input v-model:value="formData.permissionCode" placeholder="请输入权限编码" />
        </a-form-item>
        <a-form-item label="资源类型" name="resourceType">
          <a-select v-model:value="formData.resourceType" placeholder="请选择资源类型">
            <a-select-option value="menu">菜单</a-select-option>
            <a-select-option value="button">按钮</a-select-option>
            <a-select-option value="api">接口</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="资源路径" name="resourceUrl">
          <a-input v-model:value="formData.resourceUrl" placeholder="请输入资源路径（可选）" />
        </a-form-item>
        <a-form-item label="排序" name="sortOrder">
          <a-input-number
            v-model:value="formData.sortOrder"
            :min="0"
            placeholder="请输入排序值"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入权限描述（可选）"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  PlusOutlined,
  MenuOutlined,
  AppstoreOutlined,
  ApiOutlined
} from '@ant-design/icons-vue';
import { permissionApi } from './api';
import { permissionTableColumns } from './data';
import type { Permission, PermissionFormData, PermissionSearchParams } from './types';

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const isEdit = ref(false);
const editingId = ref<number | null>(null);
const permissionList = ref<Permission[]>([]);
const expandedKeys = ref<number[]>([]);
const formRef = ref();
const searchResultInfo = ref<string>('');

// 搜索表单
const searchForm = reactive<PermissionSearchParams>({
  permissionName: '',
  resourceType: undefined,
  status: undefined
});

// 表单数据
const formData = reactive<PermissionFormData>({
  parentId: null,
  permissionName: '',
  permissionCode: '',
  resourceType: 'menu',
  resourceUrl: '',
  sortOrder: 0,
  status: 1,
  description: ''
});

// 表单验证规则
const formRules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' }
  ],
  resourceType: [
    { required: true, message: '请选择资源类型', trigger: 'change' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 计算属性
const modalTitle = computed(() => {
  if (isEdit.value) {
    return '编辑权限';
  } else if (formData.parentId) {
    return '新增子权限';
  } else {
    return '新增权限';
  }
});

const parentPermissionOptions = computed(() => {
  return convertToTreeSelectData(permissionList.value);
});

// 数据转换函数
function convertToTreeSelectData(permissions: Permission[]): any[] {
  return permissions.map(permission => ({
    title: permission.permissionName,
    value: permission.id,
    key: permission.id,
    children: permission.children ? convertToTreeSelectData(permission.children) : undefined
  }));
}

// 获取权限列表
async function fetchPermissions(searchParams?: PermissionSearchParams) {
  try {
    loading.value = true;
    let response;
    
    // 如果有搜索条件，使用搜索接口；否则使用树形接口
    if (searchParams && hasSearchConditions(searchParams)) {
      response = await permissionApi.search(searchParams);
      searchResultInfo.value = `搜索到 ${countAllPermissions(response.data || [])} 条权限记录`;
    } else {
      response = await permissionApi.getTree();
      searchResultInfo.value = '';
    }
    
    permissionList.value = response.data || [];
    
    // 默认全部收起
    expandedKeys.value = [];
  } catch (error) {
    message.error('获取权限列表失败');
    searchResultInfo.value = '';
  } finally {
    loading.value = false;
  }
}

// 计算权限总数（包括子权限）
function countAllPermissions(permissions: Permission[]): number {
  let count = 0;
  for (const permission of permissions) {
    count += 1;
    if (permission.children) {
      count += countAllPermissions(permission.children);
    }
  }
  return count;
}

// 检查是否有搜索条件
function hasSearchConditions(params: PermissionSearchParams): boolean {
  return !!(
    params.permissionName?.trim() ||
    params.resourceType ||
    params.status !== undefined
  );
}

// 展开/收起功能
function expandAll() {
  const getAllKeys = (permissions: Permission[]): number[] => {
    let keys: number[] = [];
    permissions.forEach(permission => {
      keys.push(permission.id);
      if (permission.children) {
        keys = keys.concat(getAllKeys(permission.children));
      }
    });
    return keys;
  };
  expandedKeys.value = getAllKeys(permissionList.value);
}

function collapseAll() {
  expandedKeys.value = [];
}

function onExpand(expanded: boolean, record: Permission) {
  if (expanded) {
    expandedKeys.value.push(record.id);
  } else {
    const index = expandedKeys.value.indexOf(record.id);
    if (index > -1) {
      expandedKeys.value.splice(index, 1);
    }
  }
}



// 搜索和重置
function handleSearch() {
  fetchPermissions(searchForm);
}

function handleReset() {
  Object.assign(searchForm, {
    permissionName: '',
    resourceType: undefined,
    status: undefined
  });
  fetchPermissions();
}

// 模态框显示/隐藏
function showCreateModal(parent?: Permission) {
  isEdit.value = false;
  editingId.value = null;
  resetForm();
  if (parent) {
    // 新增子权限时，只设置父级ID，其他字段使用默认值
    formData.parentId = parent.id;
    // 可以根据父权限设置一些合理的默认值
    formData.sortOrder = (parent.sortOrder || 0) + 1; // 排序比父权限大1
  }
  modalVisible.value = true;
}

function showEditModal(record: Permission) {
  isEdit.value = true;
  editingId.value = record.id;
  Object.assign(formData, {
    parentId: record.parentId || null,
    permissionName: record.permissionName,
    permissionCode: record.permissionCode,
    resourceType: record.resourceType as 'menu' | 'button' | 'api',
    resourceUrl: record.resourceUrl || '',
    sortOrder: record.sortOrder,
    status: record.status,
    description: record.description || ''
  });
  modalVisible.value = true;
}

// 表单重置
function resetForm() {
  Object.assign(formData, {
    parentId: null,
    permissionName: '',
    permissionCode: '',
    resourceType: 'menu',
    resourceUrl: '',
    sortOrder: 0,
    status: 1,
    description: ''
  });
  formRef.value?.resetFields();
}

// 表单提交
async function handleSubmit() {
  try {
    await formRef.value.validate();
    
    if (isEdit.value && editingId.value) {
      await permissionApi.update(editingId.value, formData);
      message.success('权限更新成功');
    } else {
      await permissionApi.create(formData);
      message.success('权限创建成功');
    }
    
    modalVisible.value = false;
    fetchPermissions();
  } catch (error) {
    message.error(isEdit.value ? '权限更新失败' : '权限创建失败');
  }
}

// 取消操作
function handleCancel() {
  modalVisible.value = false;
  resetForm();
}

// 状态变更
async function handleStatusChange(record: Permission, checked: boolean) {
  try {
    const status = checked ? 1 : 0;
    await permissionApi.update(record.id, { ...record, status });
    record.status = status;
    message.success('状态更新成功');
  } catch (error) {
    message.error('状态更新失败');
  }
}

// 删除权限
async function handleDelete(record: Permission) {
  try {
    await permissionApi.delete(record.id);
    message.success('权限删除成功');
    fetchPermissions();
  } catch (error) {
    message.error('权限删除失败');
  }
}

// 工具方法
function getResourceTypeIcon(type: string) {
  switch (type) {
    case 'menu':
      return MenuOutlined;
    case 'button':
      return AppstoreOutlined;
    case 'api':
      return ApiOutlined;
    default:
      return MenuOutlined;
  }
}

function getResourceTypeColor(type: string) {
  switch (type) {
    case 'menu':
      return 'blue';
    case 'button':
      return 'green';
    case 'api':
      return 'orange';
    default:
      return 'default';
  }
}

function getResourceTypeText(type: string) {
  switch (type) {
    case 'menu':
      return '菜单';
    case 'button':
      return '按钮';
    case 'api':
      return '接口';
    default:
      return type;
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPermissions();
});
</script>

<style scoped>
.permission-management {
  padding: 16px;
}

.page-header {
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-area {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.action-bar {
  margin-bottom: 16px;
}

.action-bar .ant-btn {
  margin-right: 8px;
}
</style>